package com.ihealthway.all.groupbuy.services;

import com.ihealthway.all.groupbuy.vo.UserInfo;
import io.github.elkan1788.mpsdk4j.vo.api.Follower;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * User info service
 *
 * @author 凡梦星尘(elkan1788@gmail.com)
 */
@IocBean(fields = {"dao"})
public class UserInfoService extends BaseService<UserInfo> {

    private static final Log logger = Logs.get();

    public UserInfo get(String openId) {
        logger.infof("Search openId[%s] user info.", openId);
        return get("open_id", openId);
    }

    public UserInfo getRegisterUser(String openId) {
        String sqlStmt = "SELECT u.*, com.c_name AS cName FROM gb_user_info AS u " +
                "LEFT JOIN gb_company AS com ON u.c_id = com.c_id  $condition";

        Sql sql = Sqls.create(sqlStmt);
        sql.setCondition(Cnd.where("open_id", "=", openId));
        sql.setCallback(new UserInfoCallBack());
        try {
            dao().execute(sql);
        } catch (Exception e) {
            logger.error("Search exist user failure!!!", e);
        }
        List<UserInfo> users = sql.getList(UserInfo.class);
        if(users == null || users.isEmpty()) {
            return null;
        }

        return users.get(0);
    }

    public boolean updateUserInfo(UserInfo userInfo) {
        boolean updated = false;
        try {
            int rows = _updateIgnoreNull(userInfo);
            updated = (rows > 0);
        } catch (Exception e) {
            logger.error("Update user info failure!!!", e);
        }
        return updated;
    }

    public boolean saveSubscribeUser(Follower follower) {

        boolean subscribed = false;
        UserInfo userInfoTmp = get(follower.getOpenid());

        try {
            if (userInfoTmp != null && userInfoTmp.getUserId() != null) {
                userInfoTmp.cloneFromFollower(follower);
                userInfoTmp.setUnfollowTime(null);
                int rows = _update(userInfoTmp);
                subscribed = (rows > 0);
            } else {
                userInfoTmp = new UserInfo();
                userInfoTmp.cloneFromFollower(follower);
                UserInfo insertUITmp = _insert(userInfoTmp);
                subscribed = (insertUITmp!=null);
            }
        } catch (Exception e) {
            logger.error("Save subscribe user info failure!!!", e);
        }

        return subscribed;
    }

    public void updateUnSubscribeUser(String openId) {
        UserInfo userInfoTmp = get(openId);
        if (userInfoTmp!=null) {
            userInfoTmp.setUnfollowTime(new Date());
            userInfoTmp.setUpdateTime(new Date());
            userInfoTmp.setSubscribe("0");
            try {
                int rows = _updateIgnoreNull(userInfoTmp);
                if (rows < 1) {
                    logger.infof("Update user[%s] un-subscribe info failure!!!", openId);
                }
            } catch (Exception e) {
                logger.error("Update un-subscribe user info failure!!!", e);
            }
        }
    }

    public Map<String, Object> getDataList(int row, int page, String userName) {

        String sqlStmt = "SELECT u.*, com.c_name AS cName FROM gb_user_info AS u " +
                "LEFT JOIN gb_company AS com ON u.c_id = com.c_id  $condition";

        /*String sqlStmt = "SELECT u.*, com.c_name AS cName, " +
                "age.dict_name AS ageName,height.dict_name AS heightName,weight.dict_name AS weightName FROM gb_user_info AS u " +
                "LEFT JOIN (SELECT c_id, c_name FROM gb_company WHERE data_status=0) AS com ON u.c_id = com.c_id " +
                "LEFT JOIN (SELECT sd_id, dict_name,dict_value FROM gb_system_dict WHERE parent_sd_id=2) AS age ON u.age = age.sd_id " +
                "LEFT JOIN (SELECT sd_id, dict_name,dict_value FROM gb_system_dict WHERE parent_sd_id=4) AS weight ON u.weight = weight.sd_id " +
                "LEFT JOIN (SELECT sd_id, dict_name,dict_value FROM gb_system_dict WHERE parent_sd_id=3) AS height ON u.height = height.sd_id $condition";*/
        Criteria cri = Cnd.cri();
        if (Strings.isNotBlank(userName)) {
            cri.where().andEquals("u.real_name", userName);
        }
        cri.getOrderBy().desc("u.follow_time");
        Map<String, Object>  result = easyuiDGPagerWithFetch(sqlStmt, page, row, cri, new UserInfoCallBack());
        return result;
    }

    private class UserInfoCallBack implements SqlCallback {

        @Override
        public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
            List<UserInfo> users = new ArrayList<>();

            while (rs.next()) {
                UserInfo user = getEntity().getObject(rs, null, "u.");
                user.setCompanyName(rs.getString("cName"));
                /*user.setAgeName(rs.getString("ageName"));
                user.setWeightName(rs.getString("weightName"));
                user.setHeightName(rs.getString("heightName"));*/
                users.add(user);
            }

            return users;
        }
    }
}
